package cn.yusei.teamTribe.controller.user;

import java.io.PrintWriter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.service.user.EmailService;
import cn.yusei.teamTribe.util.EmailUtil;
import cn.yusei.teamTribe.util.ResponseUtil;

@Controller
public class EmailAuthController {
	
	@Autowired
	private EmailService emailService;

	private final String authUrl = "/user/authMail/auth/";
	
	@RequestMapping(value="/user/authMail/get")
	public void getAuthEmail(@RequestAttribute("id") int id, @RequestParam("email") String email, PrintWriter out)
	{
		if(id < 0 || !EmailUtil.isMailAddress(email))
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int code;
		try
		{
			code = emailService.getAuthEmail(id, email, authUrl);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		ResponseUtil.responseCode(out, code);
	}
	
	@RequestMapping(value=authUrl + "{url}")
	public void authEmail(@PathVariable("url") String url, PrintWriter out)
	{
		int code;
		try
		{
			code = emailService.authEmail(authUrl, url);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseHtml(out, "<html>系统异常</html>");
			return;
		}
		if(code == ResponseCode.URL_INVALIDATE)
		{
			ResponseUtil.responseHtml(out, "<html>URL已过期</html>");
			return;
		}
		ResponseUtil.responseHtml(out, "<html>邮箱激活成功</html>");
	}
	
}
